<template>
  <div class="loginform-container">
    <el-card class="box-card" shadow="hover">
      <h2>Welcome To Back</h2>
      <el-form
        :model="loginForm"
        status-icon
        :rules="rules"
        ref="loginForm"
        class="login-ruleForm"
      >
        <el-form-item label="" prop="username">
          <el-input
            placeholder="请输入用户账号"
            v-model="loginForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="" prop="password">
          <el-input
            placeholder="请输入用户密码"
            type="password"
            v-model="loginForm.password"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button type="success" @click="login('loginForm')">登陆</el-button>
      <el-button type="primary" @click="change">注册</el-button>
    </el-card>
  </div>
</template>

<script>
import { userLogin } from "@/api/login";
import { mapMutations } from 'vuex';

export default {
  props: {
    formType: String
  },
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户账号", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    ...mapMutations('user', ["setUserInfo"]),
    change() {
      this.$emit('update:formType', 'SigninForm')
    },
    login(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            // 
            let { data: res } = await userLogin(this.loginForm);
            console.log(res);
            if (res.meta.status == 200) {
              this.setUserInfo(res.data)
              // window.sessionStorage.setItem('token', res.data.token);
              this.$message.success(res.meta.msg);
              return this.$router.push({path: '/'})
            } else {
              return this.$message.error('登录失败！请检查账号密码')
            }
            // console.log(data);
          } else {
            // this.$message.warning('')
            return false;
          }
        });
      },
  },
};
</script>

<style lang="less" scoped>
.loginform-container {
  width: 80%;
  height: auto;
  margin: 0 auto;

  .box-card {
    .login-ruleForm {
      width: 90%;
      margin: 0 auto;
    }
  }
}
</style>